package cn.com.template.controller.budgetcalc;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cn.com.commons.Paginator;
import cn.com.commons.utils.StringUtil;
import cn.com.dal.dataobject.VerifyDO;
import cn.com.dal.dataobject.cs.BranchcostDO;
import cn.com.dal.dataobject.hr.DeptDO;
import cn.com.dal.dataobject.hr.UserDO;
import cn.com.dal.dataobject.sys.DictDO;
import cn.com.dal.dataobject.sys.VerifyConfigDO;
import cn.com.service.VerifyService;
import cn.com.service.cs.BranchcostService;
import cn.com.service.hr.DeptService;
import cn.com.service.hr.UserService;
import cn.com.service.sys.DictService;
import cn.com.service.sys.VerifyConfigService;
import cn.com.support.context.UserContext;
import cn.com.support.message.MessageResult;
import cn.com.support.utils.JacksonUtil;
import cn.com.support.utils.VerifyConfigInf;
import cn.com.template.ui.Flexigrid;
import cn.com.template.utils.FlexigridUtil;

/**
 * 
 * 分院成本控制器
 * 
 * @since 1.0 2012-2-21 下午11:03:53
 * @version $Id$
 * @author Zoe
 */
@Controller
@RequestMapping("/budgetcalc/branchcost")
public class BranchcostController {

	@Autowired
	private DictService dictService;
	
	@Autowired
	private DeptService deptService;
	
	@Autowired
	private BranchcostService branchcostService;
	
	@Autowired
	private VerifyConfigService configService;
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private VerifyService verifyService;
	
	@RequestMapping
	public ModelAndView forwardBranchcost(HttpServletRequest request) {
		ModelAndView mav = new ModelAndView("budgetcalc/branchcost");
		DeptDO deptDO = deptService.selectById(UserContext.getUser().getDeptId());
		DictDO dictDO = new DictDO();
		if(null != deptDO){
			dictDO.setModule(deptDO.getName());
		}
		List<DictDO> dictLst = dictService.selectList(dictDO);
		List<Map<String, Object>> roleIdLst = configService.getVerifyConfigRoles(VerifyConfigInf.BRANCH_COST_VERIFY).getRoleLst();
		List<UserDO> verifyLst = new ArrayList<UserDO>();
		Map<Object, Object> params = null;
		if(null != roleIdLst){
			for(Map<String, Object> roleMap : roleIdLst){
				if(roleMap.get("level").equals(1)){
					params = new HashMap<Object, Object>();
					//有效的用户
					params.put("status", 1);
					params.put("roleId", roleMap.get("id"));
					verifyLst = userService.selectListByRole(params);
					break;
				}
			}
		}
		request.setAttribute("dictLst", dictLst);
		request.setAttribute("verifyLst", verifyLst);
		return mav;
	}
	
	@RequestMapping("/getBranchCost")
	@ResponseBody
	public Flexigrid getCost(HttpServletRequest request, HttpServletResponse response){
		Flexigrid flexigrid = null;
		try {
			Paginator<BranchcostDO, List<BranchcostDO>> paginator = new Paginator<BranchcostDO, List<BranchcostDO>>();
			String refundUser = request.getParameter("refundUser");
			BranchcostDO branchcostDO = new BranchcostDO();
			if(StringUtil.isNotBlank(refundUser)){
				branchcostDO.setRefundUser(refundUser);
			}
			branchcostDO.setRefundLeader(UserContext.getUsername());
			paginator.setCondition(branchcostDO);
			// 设置分页器
			paginator.setPageSize(Integer.parseInt(request.getParameter("rp")));
			paginator.setCurrentPage(Integer.parseInt(request.getParameter("page")));
			branchcostService.selectByPage(paginator);
			//PACKAGE FLEXIGRID DATA
			flexigrid = FlexigridUtil.formatFlexigridData(paginator);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return flexigrid;
	}
	
	@RequestMapping(value="/addBranchCost", method=RequestMethod.POST)
	@ResponseBody
	public MessageResult<Long> addCost(HttpServletRequest request){
		MessageResult<Long> result = null;
		BranchcostDO branchcostDO = null;
		List<Map<String, Object>> roleIdLst = null;
		VerifyDO verifyDO = null;
		try {
			String jsonData = request.getParameter("data");
			String username = UserContext.getUsername();
			//防止js harmful数据入库
			jsonData = jsonData.replaceAll("\"", "\\\"");
			branchcostDO = (BranchcostDO) JacksonUtil.json2Bean(jsonData, BranchcostDO.class);
			branchcostDO.setRefundLeader(username);
			branchcostDO.setCreator(username);
			//设置报销状态为 创建记录但未提交报销
			branchcostDO.setStatus((byte)VerifyDO.STATUS_CREATE);
			result = branchcostService.insert(branchcostDO);
			//分院报销数据入库后
			//根据审核配置角色-用户审核关系
			//入库系统审核表
			/**
			 * 依照BJJD需求修改[day:2012.07.03]：
			 * 由用户自行提交报销
			 */
			if(result.isSucceed()){
				VerifyConfigDO configDO = configService.getVerifyConfigRoles(VerifyConfigInf.BRANCH_COST_VERIFY);
				roleIdLst = configDO.getRoleLst();
				if(null != roleIdLst){
					for(Map<String, Object> roleMap : roleIdLst){
						if(roleMap.get("level").equals(1)){
							//审核记录LEVEL:1入库
							verifyDO = new VerifyDO();
							verifyDO.setBizId(branchcostDO.getId());
							verifyDO.setVerifier(branchcostDO.getVerifier());
							verifyDO.setModule(VerifyConfigInf.BRANCH_COST_VERIFY);
							verifyDO.setLevel((byte)1);
							verifyDO.setStatus((byte)VerifyDO.STATUS_CREATE);
							verifyDO.setSort((byte)1);
							verifyDO.setAttribute(configDO.getRoleId());
							verifyDO.setCreator(username);
							//审核发起人为第一次创建人
							//所有级别的审核发起人都为同一人
							verifyDO.setSubmitter(username);
							verifyService.insert(verifyDO);
							break;
						}
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	
	//updateCost
	@RequestMapping(value="/updateCost", method=RequestMethod.POST)
	@ResponseBody
	public MessageResult<Integer> updateCost(HttpServletRequest request){
		MessageResult<Integer> result = null;
		BranchcostDO branchcostDO = null;
		VerifyDO verifyDO = null;
		try {
			String jsonData = request.getParameter("data");
			String username = UserContext.getUsername();
			//防止js harmful数据入库
			jsonData = jsonData.replaceAll("\"", "\\\"");
			branchcostDO = (BranchcostDO) JacksonUtil.json2Bean(jsonData, BranchcostDO.class);
			branchcostDO.setRefundLeader(username);
			branchcostDO.setModifier(username);
			//System.out.println(branchcostDO.toString());
			result = branchcostService.updateById(branchcostDO);
			if(result.isSucceed()){
				//update verify
				verifyDO = new VerifyDO();
				verifyDO.setId(branchcostDO.getVerifyId());
				verifyDO.setVerifier(branchcostDO.getVerifier());
				verifyDO.setModifier(username);
				verifyService.updateById(verifyDO);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	
	@RequestMapping(value="/submitVerify", method=RequestMethod.POST)
	@ResponseBody
	public MessageResult<Integer> submitVerify(@RequestParam String id, String vid){
		MessageResult<Integer> result = null;
		VerifyDO verifyDO = null;
		try {
			verifyDO = new VerifyDO();
			verifyDO.setId(Long.valueOf(vid));
			//verifyDO.setBizId(Long.valueOf(id));
			verifyDO.setStatus((byte)VerifyDO.STATUS_DOING);
			result = verifyService.updateById(verifyDO);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	
	@RequestMapping(value="/delVerify", method=RequestMethod.POST)
	@ResponseBody
	public MessageResult<Long> delVerify(@RequestParam String id, String vid){
		MessageResult<Long> result = null;
		Map<Object, Object> params = null;
		try {
			Long[] ids = new Long[]{Long.valueOf(id)};
			result = branchcostService.deleteById(ids);
			if(result.isSucceed()){
				//update verify
				params = new HashMap<Object, Object>();
				params.put("bizId", Long.valueOf(id));
				params.put("module", VerifyConfigInf.BRANCH_COST_VERIFY);
				List<VerifyDO> res = verifyService.selectList(params);
				ids = new Long[res.size()];
				int index = 0;
				for(VerifyDO verifyDO : res){
					ids[index] = verifyDO.getId(); 
					index ++;
				}
				verifyService.deleteById(ids);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	
	@RequestMapping(value="/cancalVerify", method=RequestMethod.POST)
	@ResponseBody
	public MessageResult<Integer> cancalVerify(@RequestParam String ids){
		MessageResult<Integer> result = null;
		Map<Object, Object> params = null;
		try {
			params = new HashMap<Object, Object>();
			String[] idArr = ids.split(",");
			for(String idStr: idArr){
				params.put("bizId", Long.valueOf(idStr));
				params.put("module", VerifyConfigInf.BRANCH_COST_VERIFY);
				List<VerifyDO> res = verifyService.selectList(params);
				for(VerifyDO verifyDO : res){
					//发请人取消审核
					//4:审核取消
					verifyDO.setStatus((byte)VerifyDO.STATUS_CANCEL);
					result = verifyService.updateById(verifyDO);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
}
